package net.anzhuo.controller.senior;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import lombok.extern.slf4j.Slf4j;
import net.anzhuo.common.utils.CalcUtils;
import net.anzhuo.common.utils.PageUtils;
import net.anzhuo.common.utils.RedisUtil;
import net.anzhuo.common.utils.SortUtils;
import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.db.seniorsearch.GsParam;
import net.anzhuo.entity.db.seniorsearch.Record;
import net.anzhuo.entity.es.Result;
import net.anzhuo.entity.es.SearchResult;
import net.anzhuo.service.GsBaseService;
import net.anzhuo.service.GsSeniorSearchService;

/**
 * 
 * @author jiyk
 *   高级搜索
 */
@RestController
@Slf4j
public class SeniorSearchController {

	
	@Autowired
	private TransportClient client;
	
	@Autowired
	private GsSeniorSearchService gsSeniorSearchService;
	@Autowired
	private GsBaseService gsBaseService;
	@RequestMapping("/Senior/SeniorSearch")
	public net.anzhuo.entity.db.seniorsearch.SeniorSearchResult SeniorSearch(String type,
			String searchKey,
			String SearchScope,
			String orgType,
			String enterpriseType,
			String enterpriseStatus,
			String regCapStart,
			String regCapEnd,
			String createDate,
			String regStart,
			String regEnd,
			String province,
			String city,
			String area,
			String industryType,
			String pageIndex, String pageSize) {
		log.info("===>SeniorSearch,searchKey="+searchKey+",SearchScope="+SearchScope+",orgType="+orgType+",enterpriseType="+enterpriseType+",enterpriseStatus="+enterpriseStatus+",regCapStart="+regCapStart+",regCapEnd="+regCapEnd+",createDate="+createDate+",regStart="+regStart+",regEnd="+regEnd+",province="+province+",city="+city+",area="+area+",industryType="+industryType+",pageSize="+pageSize);
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "50";
		}

		net.anzhuo.entity.db.seniorsearch.SeniorSearchResult rr = null;
		/*try {
			rr = (SeniorSearchResult)RedisUtil.get("SeniorSearchResult:");
			if (rr != null) {
				return rr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		if (StringUtils.isBlank(pageIndex) || "0".equals(pageIndex)) {
			pageIndex = "1";
		}
        GsParam base=new GsParam();
		if(SearchScope!=null)
		{
			if(SearchScope.equals("企业名"))
			{
				if(searchKey!=null)
				{
				base.setName(searchKey);
				}
			}else if(SearchScope.contains("法人"))
			{		if(searchKey!=null)
			{
				base.setLegal(searchKey);
			}
			}else if(SearchScope.contains("组织类型"))
			{
				
			}else if(SearchScope.contains("高管"))
			{
			  
			}else if(SearchScope.contains("品牌"))
			{		
		
			}else if(SearchScope.contains("联系方式"))	
			{
				if(searchKey!=null)
				{
			  base.setTel(searchKey);
				}
			}else if(SearchScope.contains("经营范围"))
			{		if(searchKey!=null)
			{
		     base.setOperScope(searchKey);
			}
			}
		}else {
			if(searchKey!=null)
			{
			base.setName(searchKey);
			}
		}
		if(enterpriseType!=null)
		{
			base.setEnterpriseType(enterpriseType);
		}
		if(enterpriseStatus!=null)
		{
			base.setEnterpriseStatus(enterpriseStatus);
		}
		if(regCapStart!=null&&regCapEnd!=null)
		{
			base.setRegZb_Start(regCapStart);;
			base.setRegZb_End(regCapEnd);
		}
		
		if(createDate!=null)
		{
			base.setRegTime(createDate);
		}else
		{
			base.setRegTimeStart(regStart);
			base.setRegTimeEnd(regEnd);
		}
		
		if(province!=null)
		{
			base.setProvince(province);
		}
		if(city!=null)
		{
			base.setCity(city);
		}
		
		if(area!=null)
		{
			base.setArea(area);
		}
		if(industryType!=null)
		{
			base.setIndustry(industryType);
		}

        //es search
		//QueryBuilder query=null;
		BoolQueryBuilder query=QueryBuilders.boolQuery();
		if(base.getName()!=null)
		{
		query.must(QueryBuilders.boolQuery()
					.should(QueryBuilders.matchQuery("name", searchKey).operator(Operator.AND)))
				.must(QueryBuilders.boolQuery());
		        
		}else if(base.getLegal()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("legal", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
						
		}else if(base.getTel()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("tel", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
		}else if(base.getOperScope()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("oper_scope", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
		}
	
		//orgType
		
		//enterprise_type
		if(enterpriseType!=null)
		{

			query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("enterprise_type", enterpriseType).operator(Operator.AND)));
		}
		//enterpriseStatus
		if(enterpriseStatus!=null)
		{
			query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("enterprise_status", enterpriseStatus).operator(Operator.AND)));
		}
		//regCapStart regCapEnd
		if(regCapStart!=null&&regCapEnd!=null)
		{        
			query.must((new RangeQueryBuilder("reg_zb").gt(regCapStart).lt(regCapEnd)));
		}
		//createDate
		if(createDate!=null)
		{        
			query.must(new QueryStringQueryBuilder(createDate).field("year"));
		}
		//regStart regEnd
		if(regStart!=null&&regEnd!=null)
		{        
			query.must((new RangeQueryBuilder("reg_time").gt(regStart).lt(regEnd)));
		}
		
		//province
		if(province!=null)
		{        
			query.must(new QueryStringQueryBuilder(province).field("province"));
		}
		
		//city
		if(city!=null)
		{        
			query.must(new QueryStringQueryBuilder(city).field("city"));
		}
		
		//area
		if(area!=null)
		{        
			query.must(new QueryStringQueryBuilder(area).field("area"));
		}
		
		//industryType
		if(industryType!=null)
		{        
			query.must(new QueryStringQueryBuilder(industryType).field("industry"));
		}
			
		SearchResponse response  = client.prepareSearch("gs").setTypes("gs_base").setQuery(query)
				.setSearchType(SearchType.QUERY_THEN_FETCH)
				.setScroll(new TimeValue(600000)).setSize(10000).execute().actionGet();

		SearchResult searchResult = new SearchResult();
		searchResult.setStatus("200");
		searchResult.setMessage("查询成功");
		
		net.anzhuo.entity.es.Paging paging = new net.anzhuo.entity.es.Paging();
		paging.setPageIndex(Integer.parseInt(pageIndex));
		//paging.setPageSize(pageSize);
		paging.setTotalRecords((int)response.getHits().getTotalHits());
		searchResult.setPaging(paging);
		
		log.info("SeniorSearch's length="+response.getHits().getTotalHits());
		List<GsBase> list=new ArrayList<GsBase>();
			for (SearchHit searchHit : response.getHits()) {
				
				GsBase gs=new GsBase();

				gs.setProvince((String)searchHit.getSource().get("province"));
				gs.setCity((String)searchHit.getSource().get("city"));
				gs.setCity((String)searchHit.getSource().get("area"));
				gs.setEnterpriseStatus((String)searchHit.getSource().get("enterprise_status"));
				gs.setEnterpriseType((String)searchHit.getSource().get("enterprise_type"));
				gs.setRegZb((String)searchHit.getSource().get("reg_zb"));
				gs.setRegTime((String)searchHit.getSource().get("year"));
				gs.setIndustry((String)searchHit.getSource().get("industry"));
				gs.setMd5((String)searchHit.getSource().get("md5"));
				gs.setName((String)searchHit.getSource().get("name"));
				
				list.add(gs);
			}
	
		
		//List<GsBase> list=gsBaseService.getList();
		CalcUtils cu=new CalcUtils();
		cu.calc(list);
		Hashtable<String,Integer> ht1=cu.getEnterpriseStatus();
		
		Hashtable<String,Integer> ht2=cu.getRegTime();
		
		Hashtable<String,Integer> ht3=cu.getProvince();
		
		Hashtable<String,Integer> ht4=cu.getCity();
		
		Hashtable<String,Integer> ht5=cu.getArea();
		Hashtable<String,Integer> ht6=cu.getIndustry();
		

	
		rr=new net.anzhuo.entity.db.seniorsearch.SeniorSearchResult();
		//EnterpriseStatus
		List<Record> enterpriseStatusR=new ArrayList<Record>();
	
		Record r=new Record();
	
			for(Map.Entry<String, Integer> entry: ht1.entrySet()){
				r=new Record();
				r.setRecordName(entry.getKey());
				r.setRecordCount(entry.getValue());
				enterpriseStatusR.add(r);
				}
				
			
		
		//EnterpriseStartDate
		List<Record> EnterpriseStartDateR=new ArrayList<Record>();

		for(Map.Entry<String, Integer> entry: ht2.entrySet()){
				r=new Record();
				r.setRecordName(entry.getKey());
				r.setRecordCount(entry.getValue());
				EnterpriseStartDateR.add(r);
			}
		
		//Province
		List<Record> Province=new ArrayList<Record>();

		for(Map.Entry<String, Integer> entry: ht3.entrySet())
			{
				r=new Record();
				r.setRecordName(entry.getKey());
				r.setRecordCount(entry.getValue());
				Province.add(r);
			}
			
	    //city
			List<Record> city1=new ArrayList<Record>();

			for(Map.Entry<String, Integer> entry1: ht4.entrySet())
				{
					r=new Record();
					r.setRecordName(entry1.getKey());
					r.setRecordCount(entry1.getValue());
					city1.add(r);
				}
				
				
	     //area
				List<Record> area1=new ArrayList<Record>();

				for(Map.Entry<String, Integer> entry2: ht5.entrySet())
					{
						r=new Record();
						r.setRecordName(entry2.getKey());
						r.setRecordCount(entry2.getValue());
						area1.add(r);
					}
		
		//IndustryCategory
		List<Record> industryCategory=new ArrayList<Record>();
		for(Map.Entry<String, Integer> entry3: ht6.entrySet())
			{
				r=new Record();
				r.setRecordName(entry3.getKey());
				r.setRecordCount(entry3.getValue());
				industryCategory.add(r);
			}
		rr.setEnterpriseStatus(enterpriseStatusR);
		rr.setEnterpriseStartDate(EnterpriseStartDateR);
		rr.setProvince(Province);
		rr.setCity(city1);
		rr.setArea(area1);
		rr.setIndustryCategory(industryCategory);
		try {
			RedisUtil.set("SeniorSearchResult:", rr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return rr;
	}
	
	
	
	@RequestMapping("/Senior/SeniorSearchResult")
	public SearchResult SeniorSearchResult(String type,
			String searchKey,
			String SearchScope,
			String orgType,
			String enterpriseType,
			String enterpriseStatus,
			String regCapStart,
			String regCapEnd,
			String createDate,
			String regStart,
			String regEnd,
			String province,
			String city,
			String area,
			String industryType,
			String orderType,
			String pageIndex, String pageSize) {
		log.info("===>SeniorSearch,searchKey="+searchKey+",SearchScope="+SearchScope+",orgType="+orgType+",enterpriseType="+enterpriseType+",enterpriseStatus="+enterpriseStatus+",regCapStart="+regCapStart+",regCapEnd="+regCapEnd+",createDate="+createDate+",regStart="+regStart+",regEnd="+regEnd+",province="+province+",city="+city+",area="+area+",industryType="+industryType+",orderType="+orderType+",pageSize="+pageSize);
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "50";
		}
		long startTime=System.currentTimeMillis();
		SearchResult rr = null;
		/*try {
			rr = (SeniorSearchResult)RedisUtil.get("SeniorSearchResult:");
			if (rr != null) {
				return rr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		if (StringUtils.isBlank(pageIndex) || "0".equals(pageIndex)) {
			pageIndex = "1";
		}
        GsParam base=new GsParam();
		if(SearchScope!=null)
		{
			if(SearchScope.equals("企业名"))
			{
				if(searchKey!=null)
				{
				base.setName(searchKey);
				}
			}else if(SearchScope.contains("法人"))
			{		if(searchKey!=null)
			{
				base.setLegal(searchKey);
			}
			}else if(SearchScope.contains("组织类型"))
			{
				
			}else if(SearchScope.contains("高管"))
			{
			  
			}else if(SearchScope.contains("品牌"))
			{		
		
			}else if(SearchScope.contains("联系方式"))	
			{
				if(searchKey!=null)
				{
			  base.setTel(searchKey);
				}
			}else if(SearchScope.contains("经营范围"))
			{		if(searchKey!=null)
			{
		     base.setOperScope(searchKey);
			}
			}
		}else {
			if(searchKey!=null)
			{
			base.setName(searchKey);
			}
		}
		if(enterpriseType!=null)
		{
			base.setEnterpriseType(enterpriseType);
		}
		if(enterpriseStatus!=null)
		{
			base.setEnterpriseStatus(enterpriseStatus);
		}
		if(regCapStart!=null&&regCapEnd!=null)
		{
			base.setRegZb_Start(regCapStart);;
			base.setRegZb_End(regCapEnd);
		}
		
		if(createDate!=null)
		{
			base.setRegTime(createDate);
		}else
		{
			base.setRegTimeStart(regStart);
			base.setRegTimeEnd(regEnd);
		}
		
		if(province!=null)
		{
			base.setProvince(province);
		}
		if(city!=null)
		{
			base.setCity(city);
		}
		
		if(area!=null)
		{
			base.setArea(area);
		}
		if(industryType!=null)
		{
			base.setIndustry(industryType);
		}

        //es search
		/*QueryBuilder query=null;
		
		if(base.getName()!=null)
		{
		query = QueryBuilders.boolQuery()
				.must(QueryBuilders.boolQuery()
					.should(QueryBuilders.matchQuery("name", searchKey).operator(Operator.AND)))
				.must(QueryBuilders.boolQuery()
					.should(QueryBuilders.matchPhraseQuery("enterprise_type", "有限责任公司"))
					.should(QueryBuilders.matchPhraseQuery("enterprise_type", "股份有限公司")));
		}else if(base.getLegal()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("legal", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "有限责任公司"))
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "股份有限公司")));
		}else if(base.getTel()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("tel", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "有限责任公司"))
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "股份有限公司")));
		}else if(base.getOperScope()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("oper_scope", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "有限责任公司"))
						.should(QueryBuilders.matchPhraseQuery("enterprise_type", "股份有限公司")));
		}
	*/
		 //es search
		//QueryBuilder query=null;
		BoolQueryBuilder query=QueryBuilders.boolQuery();
		if(base.getName()!=null)
		{
		query.must(QueryBuilders.boolQuery()
					.should(QueryBuilders.matchQuery("name", searchKey).operator(Operator.AND)))
				.must(QueryBuilders.boolQuery());
		        
		}else if(base.getLegal()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("legal", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
						
		}else if(base.getTel()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("tel", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
		}else if(base.getOperScope()!=null)
		{
			query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.should(QueryBuilders.matchQuery("oper_scope", searchKey).operator(Operator.AND)))
					.must(QueryBuilders.boolQuery());
		}
	
		//orgType
		
		//enterprise_type
		if(enterpriseType!=null)
		{

			query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("enterprise_type", enterpriseType).operator(Operator.AND)));
		}
		//enterpriseStatus
		if(enterpriseStatus!=null)
		{
			query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("enterprise_status", enterpriseStatus).operator(Operator.AND)));
		}
		//regCapStart regCapEnd
		if(regCapStart!=null&&regCapEnd!=null)
		{        
		    query.must((new RangeQueryBuilder("reg_zb").gt(regCapStart).lt(regCapEnd)));
		}
		//createDate
		if(createDate!=null)
		{        
			query.must(new QueryStringQueryBuilder(createDate).field("year"));
		}
		//regStart regEnd
		if(regStart!=null&&regEnd!=null)
		{        
			query.must((new RangeQueryBuilder("reg_time").gt(regStart).lt(regEnd)));
		}
		
		//province
		if(province!=null)
		{        
			query.must(new QueryStringQueryBuilder(province).field("province"));
		}
		
		//city
		if(city!=null)
		{        
			query.must(new QueryStringQueryBuilder(city).field("city"));
		}
		
		//area
		if(area!=null)
		{        
			query.must(new QueryStringQueryBuilder(area).field("area"));
		}
		
		//industryType
		if(industryType!=null)
		{        
			query.must(new QueryStringQueryBuilder(industryType).field("industry"));
		}
			
		
		SearchResponse response =null;
		String flag="00";
		//response=client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt(pageIndex)-1)*Integer.parseInt(pageSize)).setSize(Integer.parseInt(pageSize)).execute().actionGet();
		response=client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom(0).setSize(10000).execute().actionGet();
		if(orderType!=null) {
		if(orderType.equals("成立日期升序"))
		{
		 flag="01";
		}else if(orderType.equals("成立日期降序"))
		{
		 flag="02";
		}else if(orderType.equals("注册资本升序"))
		{
	     flag="03";
		}else if(orderType.equals("注册资本降序"))
		{
	     flag="04";
		}
		
		}
		log.info("seniorResult's length="+ response.getHits().getTotalHits());
		SearchResult searchResult = new SearchResult();
		searchResult.setStatus("200");
		searchResult.setMessage("查询成功");
		
		net.anzhuo.entity.es.Paging paging = new net.anzhuo.entity.es.Paging();
		paging.setPageIndex(Integer.parseInt(pageIndex));
		paging.setPageSize(Integer.parseInt(pageSize));
		paging.setTotalRecords((int)response.getHits().getTotalHits());
		searchResult.setPaging(paging);
		
		Result result = null;
		List<Result> resultList = new ArrayList<>();

			for (SearchHit searchHit : response.getHits()) {			
				result = new Result();
				result.setKeyNo((String)searchHit.getSource().get("md5"));
				result.setName((String)searchHit.getSource().get("name"));
				result.setOperName((String)searchHit.getSource().get("legal"));
				result.setStartDate((String)searchHit.getSource().get("reg_time"));
				result.setStatus((String)searchHit.getSource().get("enterprise_status"));
				result.setCreditCode((String)searchHit.getSource().get("credit_code"));
				result.setRegCap((String)searchHit.getSource().get("reg_zb"));
				resultList.add(result);
			}
	//sort
    SortUtils su=new SortUtils(resultList,flag);
    resultList=su.result;
    PageUtils pu=new PageUtils(resultList,Integer.parseInt(pageIndex),Integer.parseInt(pageSize));
    resultList=pu.result;
	log.info("SeniorSearch Result:resultList'size="+resultList.size());
			searchResult.setResult(resultList);
			 long endTime=System.currentTimeMillis();
			 float excTime=(float)(endTime-startTime)/1000;
			 log.info(" SeniorSearch 执行时间："+excTime+"s");
			return searchResult;
	
	}
	
	
			
	
	
	
	
}
